<?php

namespace Buu\Modules\EventSystem\Controllers;

use Adldap\Models\ModelNotFoundException;
use App\Models\Consumer;
use App\Models\K8S;
use App\Models\MaxwellInstance;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Models\ConsumerChannel;
use Encore\Admin\Controllers\AdminController;
use Hhz\Drone\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class ChannelController extends AdminController
{
    private const DEPLOY_CONFIG_File = "DroneConfigMap.json";
    public static array $aDroneConfig = [];


    public function __construct()
    {
        $dir = dirname( __DIR__) . "/Lib/" . self::DEPLOY_CONFIG_File;
        $sConfig = file_get_contents($dir);
        $configMap = json_decode($sConfig, true, 512, JSON_THROW_ON_ERROR);

        self::$aDroneConfig = $configMap['distribution'];
    }

    /**
     * title
     * @return string
     */
    protected function title()
    {
        return "分发实例管理";
    }

    /**
     * 列表构建
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ConsumerChannel());
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableBatchActions();
        $grid->column('id', 'ID')->sortable();
        $grid->column('name', '分发者');
        $grid->column('consumers', '关联消费者')->display(function () {
            return Consumer::where('consumer_channel_id',$this->id)->pluck('name');
        })->label()->width(360);
        $grid->column('backlog', '消息堆积数量');
        $grid->column('in_qps', '流入速率（条/秒）');
        $grid->column('out_qps', '流出速率（条/秒）');
        $grid->column('deployment_status', '运行状态')->label(K8S::WORKLOAD_STATUS_LABEL);
        $grid->actions(function ($actions) {
            $actions->disableDelete();
//            $actions->disableEdit();
//            $actions->disableView();
                $actions->append("<a style='color: green; margin-left: 10px;' href='channel/operate-create/{$actions->row->id}'><i class='fa fa-cogs'></i>重载</a>");
        });
        return $grid;
    }


    /**
     * 表单.
     *
     * @return Form
     */
    public function form()
    {
        $form = new Form(new ConsumerChannel());

        $form->text('name', '分发者名称')->rules('required');
        $form->text('url', '请求地址')->rules('required|url');
        $form->text('custom_url', '通配符域名')->rules('required|url', [
            'required' => '必填字段',
            'url' => '必须是http/https',
        ])->help("仅支持通配符 {{HHZVAR}} 作为变量使用，例如：tapi.{{HHZVAR}}");;
        // 设置校验规则
        $form->keyValue('env_list');

        $form->saving(function (Form $form) {
        });
        $form->tools(function (Form\Tools $tools) {
//            $tools->disableView();
            $tools->disableDelete();
        });

        return $form;
    }

    /**
     * 查看详情
     * @param $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ConsumerChannel::findOrFail($id));
        $show->field('id', 'ID');
        $show->field('name', '渠道');
        $show->field('url', '请求地址');
        $show->field('custom_url', '通配符域名');
        $show->panel()->tools(function ($tools) {
//                $tools->disableEdit();
//                $tools->disableList();
            $tools->disableDelete();
        });;
        return $show;
    }

    public function operateCreate(Request $request, $id)
    {
        try {
            $branch = self::$aDroneConfig['branch'];
            $globalConfig = self::$aDroneConfig['global_config'];
            if (HhzEnv::isProduction()) {
                $globalConfig = $globalConfig['production'];
            } else {
                $globalConfig = $globalConfig['qa'];
            }
            //获取环境变量
            $ConsumerChannel = ConsumerChannel::find($id)->toArray();
            $parameters = ['CHANNELID' => $id];
            if(!empty($ConsumerChannel['env_list'])) {
                $parameters = array_merge($parameters, $ConsumerChannel['env_list']);
            }
            $this->drone($globalConfig['target'], $parameters,
                self::$aDroneConfig['drone_address'],
                $branch);
        } catch (\Exception $e) {
            admin_toastr('操作失败' . $e->getMessage(), 'error', ['timeOut' => 5000]);
            return redirect('/admin/EventSystem/channel');
        }
        admin_toastr('操作成功', 'success', ['timeOut' => 5000]);
        return redirect('/admin/EventSystem/channel');
    }

    public function operateStop(Request $request, $id)
    {
        if ($id <= 0) {
            $error = new MessageBag([
                'title' => 'id不能小于等于0',
            ]);
            return back()->with(compact('error'));
        }
        try {
            $consumerChannel = ConsumerChannel::findOrFail($id);
        } catch (\Exception $e) {
            admin_toastr('无效的ID', 'error', ['timeOut' => 5000]);
            return redirect('/admin/EventSystem/channel');
        }
        $sMsg = ConsumerChannel::SetOperate($id, MaxwellInstance::OPERATE_STOP);
        admin_toastr($sMsg, 'success', ['timeOut' => 5000]);
        return redirect('/admin/EventSystem/channel');
    }

    /**
     * 部署无人机
     */
    public function drone(
        string $target,
        array $parameters,
        string $sPromotePath,
        $branch = 'master'
    ) {
        Log::info('部署 :' . $sPromotePath . '--' . $branch . '--' . $target, $parameters);

        $drone = new Gateway(
            'https://drone.haohaozhu.me/api/',
            'nFIBGyqDaNe0N4iS33ir9SAPg54nVAQ3'
        );
        sleep(1);
        return $drone->Promote($sPromotePath, $target, $parameters, $branch);
    }
}